import { Layout, Input, Button, message } from "antd";
import React, { useState, useEffect } from "react";
import { Table, Tag, Select, DatePicker, Space, Popconfirm } from "antd";
import { SearchOutlined, RedoOutlined, PlusOutlined } from "@ant-design/icons";
import type { TableProps } from "antd";
import dayjs from "dayjs";
import AddData from "./AddDataForm";
import ImgLoading from "@/components/ImgLoading";
import { IdataType, ItagType, ItagInfo } from "@/types/type";
import { useTranslation } from "react-i18next";
import { createPaginationProps } from "@/types/antdfc";
import { fangdou } from "@/types/myfc";
import {
  getTag,
  getData,
  deleteData,
  addData,
  editData,
} from "@/service/myrequest";
import { ConfigProvider } from "antd";
import zhCN from "antd/es/locale/zh_CN";
import enCN from "antd/es/locale/en_US";
import { selectLang } from "@/redux/reducer";
import { useSelector } from "react-redux";

const { RangePicker } = DatePicker;
const { Header, Content } = Layout;

const DataPage: React.FC = () => {
  const { t } = useTranslation();
  const nowLang = useSelector(selectLang);
  const [dialog, setDialog] = useState("");
  const [open, setOpen] = useState(false);
  const [nowitem, setNowitem] = useState<IdataType>();
  const [dataSource, setDataSource] = useState<IdataType[]>([]);
  const [pageOption, setPageOption] = useState({
    pageNo: 1,
    pageSize: 8,
  });
  const [total, setTotal] = useState(0);
  const [tags, setTags] = useState<ItagType[]>([]);
  const [searchName, setSearchName] = useState("");
  const [searchTag, setSearchTag] = useState<string[]>([]);
  const [startTime, setStartTime] = useState<number>(0);
  const [endTime, setEndTime] = useState<number>(0);

  // 列表列定义
  const columns: TableProps<IdataType>["columns"] = [
    {
      title: t("table.serial"),
      width: "6%",
      key: "index",
      align: "center",
      render(_: any, __: any, index: number) {
        return (pageOption.pageNo - 1) * 10 + index + 1;
      },
    },
    {
      title: t("table.linkurl"),
      width: "9%",
      dataIndex: "url",
      key: "url",
      align: "center",
      render: (record: string) => (
        <ImgLoading src={`${import.meta.env.VITE_TARGET}/upload/${record}`} />
      ),
    },
    {
      title: t("table.name"),
      width: "14%",
      dataIndex: "name",
      key: "name",
    },
    {
      title: t("table.desc"),
      width: "16%",
      dataIndex: "description",
      key: "description",
      ellipsis: true,
    },
    {
      title: t("table.addtime"),
      width: "14%",
      dataIndex: "time",
      key: "time",
      render: (record: number) => dayjs(record).format("YYYY-MM-DD HH:mm:ss"),
    },
    {
      title: t("table.tag"),
      width: "30%",
      dataIndex: "tagsInfo",
      key: "tagsInfo",
      ellipsis: true,
      render: (record: ItagInfo[]) => (
        <>
          {record.map(tag => {
            return (
              <Tag color={tag.color} key={tag.name}>
                {tag.name}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: t("table.action"),
      key: "id",
      width: "11%",
      render: (record: IdataType) => (
        <Space size="middle" style={{ height: "100%" }}>
          <a style={{ color: "#1677FF" }} onClick={() => showEdit(record)}>
            {t("table.edit")}
          </a>
          <Popconfirm
            okText={t("confirm")}
            cancelText={t("cancel")}
            title={t("deltxt")}
            onConfirm={() => {
              handleDelete(record);
            }}
          >
            <a style={{ color: "#FF4D4F" }}>{t("table.delete")}</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  useEffect(() => {
    localData();
  }, [pageOption]);

  useEffect(() => {
    getTag().then(tags => setTags(tags));
  }, []);

  //查询
  const localData = () => {
    const params = {
      ...pageOption,
      name: searchName,
      tags: searchTag,
      startTime: startTime,
      endTime: endTime,
    };
    getData(params).then(data => {
      setDataSource(data.dataInfo);
      setTotal(data.pageInfo.total);
    });
  };

  //分页
  const changePage = (pageNo: number, pageSize: number) => {
    setPageOption({ ...pageOption, pageNo: pageNo, pageSize: pageSize });
  };

  //删除数据
  const handleDelete = (item: IdataType) => {
    const id = item.id;
    deleteData(id).then(() => {
      message.success(t("delsu"));
      localData();
    });
  };

  //重置
  const handleReset = () => {
    setSearchName("");
    setSearchTag([]);
    setStartTime(0);
    setEndTime(0);
    setPageOption({
      ...pageOption,
      pageNo: 1,
    });
  };

  //添加数据
  const handleAdd = (newdata: IdataType) => {
    addData(newdata).then(() => {
      message.success(t("addsu"));
      localData();
    });
    setOpen(false);
  };

  //修改数据
  const handleEdit = (updata: IdataType) => {
    editData(updata).then(() => {
      message.success(t("editsu"));
      localData();
    });
    setOpen(false);
  };

  //显示添加弹窗
  const showAdd = () => {
    setDialog("Add");
    setOpen(true);
  };

  //显示编辑弹窗
  const showEdit = (item: IdataType) => {
    setNowitem(item);
    setDialog("Edit");
    setOpen(true);
  };

  //取消弹窗
  const handleCancel = () => {
    setOpen(false);
  };
  return (
    <ConfigProvider locale={nowLang === "zh" ? zhCN : enCN}>
      <Layout>
        {/* 搜索栏 */}
        <Header
          style={{
            background: "#fff",
            boxSizing: "content-box",
            padding: 0,
            display: "flex",
            alignItems: "center",
            justifyContent: "space-evenly",
            borderRadius: "5px",
          }}
        >
          {/* 名称 */}
          <span>
            {t("header.name")}
            <Input
              style={{ width: "200px" }}
              onChange={e => setSearchName(e.target.value)}
              placeholder={t("header.namep")}
              showCount
              maxLength={20}
              value={searchName}
            />
          </span>

          {/* 标签 */}
          <span className="my-search-tag">
            {t("header.tag")}
            <Select
              mode="multiple"
              style={{ width: "200px" }}
              placeholder={t("header.tagp")}
              value={searchTag}
              onChange={value => {
                setSearchTag(value);
              }}
              options={tags.map((tag: ItagType) => ({
                value: tag.id,
                label: tag.name,
              }))}
            />
          </span>

          {/* 时间 */}
          <span>
            {t("header.addtime")}
            <RangePicker
              showTime
              minDate={dayjs("1970-01-01")}
              allowEmpty={[true, true]}
              value={[
                startTime ? dayjs(startTime) : undefined,
                endTime ? dayjs(endTime) : undefined,
              ]}
              id={{ start: "开始时间", end: "结束时间" }}
              onChange={(_, timeString) => {
                setStartTime(
                  timeString[0] === "" ? 0 : dayjs(timeString[0]).valueOf()
                );
                setEndTime(
                  timeString[1] === "" ? 0 : dayjs(timeString[1]).valueOf()
                );
              }}
              style={{ width: "350px" }}
            />
          </span>

          {/* 搜索按钮 */}
          <Button type="primary" onClick={fangdou(localData, 500)}>
            <SearchOutlined />
            {t("header.search")}
          </Button>

          {/* 重置按钮 */}
          <Button onClick={fangdou(handleReset, 500)}>
            <RedoOutlined />
            {t("header.reset")}
          </Button>
        </Header>
        <Content
          style={{
            backgroundColor: "#FFFFFF",
            margin: "10px 0",
            borderRadius: "10px",
            padding: " 0 1rem",
          }}
        >
          {/* 添加数据按钮 */}
          <div style={{ textAlign: "right", padding: "1rem 0" }}>
            <Button type="primary" onClick={showAdd}>
              <PlusOutlined />
              {t("table.adddata")}
            </Button>
            <AddData
              open={open}
              dialog={dialog}
              close={handleCancel}
              editok={handleEdit}
              addok={handleAdd}
              tags={tags}
              data={dialog === "Edit" ? nowitem : undefined}
            />
          </div>

          {/* 数据表格+分页 */}
          <Table
            bordered={true}
            dataSource={dataSource}
            columns={columns}
            pagination={createPaginationProps(
              total,
              pageOption.pageSize,
              changePage
            )}
            style={{ minHeight: "522px" }}
          ></Table>
        </Content>
      </Layout>
    </ConfigProvider>
  );
};

export default DataPage;
